package com.neusoft.neuiotms.dcom.converter.problem;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.problem.ProblemHandlingDTO;
import com.neusoft.neuiotms.dcom.model.problem.ProblemHandling;
import com.neusoft.neuiotms.dcom.model.problem.ProblemHandlingAttachment;
import com.neusoft.neuiotms.dcom.repository.problem.ProblemHandlingRepository;

@Component
public class ProblemHandlingConverter extends AbstractConverter<ProblemHandling, ProblemHandlingDTO> {

    @Autowired
    private ProblemHandlingRepository problemHandlingRepository;

    @Autowired
    private ProblemHandlingAttachmentConverter problemHandlingAttachmentConverter;

    @Override
    public ProblemHandling toModel(final ProblemHandlingDTO dto) {
        ProblemHandling model;
        if (dto.isNew()) {
            model = new ProblemHandling();
        } else {
            model = this.problemHandlingRepository.getOne(dto.getId());
        }
        model.setTaskId(dto.getTaskId());
        model.setWorkOrderNum(dto.getWorkOrderNum());
        if ((dto.getAttachments() != null) && !dto.getAttachments().isEmpty()) {
            final List<ProblemHandlingAttachment> list =
                    this.problemHandlingAttachmentConverter.toListModel(dto.getAttachments());
            list.forEach(t -> {
                t.setProblemHandling(model);
            });
            model.setAttachments(list);
        }
        model.setProblemCause(dto.getProblemCause());
        model.setPlan(dto.getPlan());
        model.setResult(dto.getResult());
        model.setUnfinishedCause(dto.getUnfinishedCause());
        model.setUpdateTime(new Date());
        return model;
    }

    @Override
    public ProblemHandlingDTO toDTO(final ProblemHandling model, final boolean forListView) {
        final ProblemHandlingDTO dto = new ProblemHandlingDTO();
        dto.setTaskId(model.getTaskId());
        dto.setWorkOrderNum(model.getWorkOrderNum());
        dto.setId(model.getId());
        if (!forListView) {
            dto.setAttachments(
                    this.problemHandlingAttachmentConverter.toListDTO(model.getAttachments()));
        }
        dto.setProblemCause(model.getProblemCause());
        dto.setPlan(model.getPlan());
        dto.setResult(model.getResult());
        dto.setUnfinishedCause(model.getUnfinishedCause());
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());

        return dto;
    }

}
